package crypto

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io"
	"regexp"
	"strconv"
	"strings"
)

// 二次加密密码
// password 用户md5密码
// id 随机时间戳
func (cry *Crypto) PWEncode(password string, id string) (*string, error) {
	suffix := password[(len(password) - 1):]
	num := regexp.MustCompile("^[0-9]$")
	abc := regexp.MustCompile("^[a-zA-Z]")
	index := 0
	var err error
	if num.MatchString(suffix) {
		index, err = strconv.Atoi(suffix)
		if err != nil {
			index = 10
		}
	} else if abc.MatchString(suffix) {
		str := strings.ToLower(suffix)
		for _, char := range str {
			index = int(char) - int('a') + 10
		}
	}
	pw := fmt.Sprintf("%s%s", password, id[index:])
	return cry.PWMd5(pw)
}

// md5生成密码
func (cry *Crypto) PWMd5(value string) (*string, error) {
	md := md5.New()
	if _, err := io.WriteString(md, value); err != nil {
		return nil, err
	}
	val := hex.EncodeToString(md.Sum(nil))
	return &val, nil
}

// 密码比对
func (cry *Crypto) PWVerify(password string, pw string, id string) bool {
	val, err := cry.PWEncode(pw, id)
	if err != nil {
		return false
	}
	return Verify(password, *val)
}
